package com.sgb.contract.view.ui.openaccount;

import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.sgb.contract.BR;
import com.sgb.contract.R;
import com.sgb.contract.base.BaseActivity;
import com.sgb.contract.databinding.ContractActivityOpenAccountBinding;
import com.sgb.contract.test.model.OpenAccountEntity;
import com.sgb.contract.utils.ArouterConfigs;
import com.sgb.contract.utils.StringUtils;
import com.sgb.contract.view.ui.accountdetail.AccountDetailActivity;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.MToast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;


/**
 * 在线合同开户
 *
 * @author chentao
 */
@Route(path = ArouterConfigs.AR_OPEN_ACCOUNT)
public class OpenAccountActivity extends BaseActivity<ContractActivityOpenAccountBinding, OpenAccountViewModel> implements View.OnFocusChangeListener, TextWatcher {

    private boolean isAgree = true;//是否勾选
    private boolean isGetCode;//是否获取过验证码
    private OpenAccountEntity bean;
    private int startIndex;

    @Override
    protected int getLayoutResId() {
        return R.layout.contract_activity_open_account;
    }

    @Override
    protected void initViewModel() {
        mViewModel = createViewModel(OpenAccountViewModel.class, BR.mAccountDetailViewModel);
    }// 列表  详情

    public static void start(Context context) {
        Intent intent = new Intent(context, OpenAccountActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }


    @Override
    protected void init() {
        mDataBinding.head.title.setText(R.string.name_title_open_account);
        mDataBinding.head.ivBack.setOnClickListener(v -> finish());
        mDataBinding.agreeImg.setOnClickListener(v -> {
            isAgree = !isAgree;
            mDataBinding.agreeImg.setImageResource(isAgree ? R.mipmap.icon_hetong_select_checkbox_item : R.mipmap.icon_hetong_no_select_item);
        });
        mDataBinding.openAccountProtocol.setOnClickListener(v -> {
            //跳转协议
            startActivity(new Intent(OpenAccountActivity.this, WebViewActivity.class));
        });
        mDataBinding.getCode.setOnClickListener(v -> {
                    if (TextUtils.isEmpty(mDataBinding.edPhone.getText())) {
                        mDataBinding.txtTipPhone.setText("请输入手机号码");
                        mDataBinding.txtTipPhone.setVisibility(View.VISIBLE);
                        return;
                    }
                    isGetCode = true;
                    mViewModel.getValidateCode(OpenAccountActivity.this, mDataBinding.edPhone.getText().toString());
                }
        );
        mDataBinding.edPhone.setOnFocusChangeListener(this);
        mDataBinding.edPhone.addTextChangedListener(this);
        mDataBinding.verificationCode.setOnFocusChangeListener(this);
        mDataBinding.verificationCode.addTextChangedListener(this);
        mDataBinding.name.setOnFocusChangeListener(this);
        mDataBinding.name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                startIndex = start;
                if (!TextUtils.isEmpty(mDataBinding.name.getText().toString())) {
                    mDataBinding.txtTipName.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String temp = s.toString();
                int length = temp.length();
                if (!isLegalName(temp) && (length - 1) >= 0) {
                    s.delete(startIndex, startIndex + 1);
                }
            }
        });
        mDataBinding.idNum.setOnFocusChangeListener(this);
        mDataBinding.idNum.addTextChangedListener(this);
        mDataBinding.imgTip1.setOnClickListener(v -> {
            new RoundDialog.Builder(this)
                    .title("提示")
                    .content("用于接收电子签章验证码的手机号，暂不支持修改")
                    .confirm("知道了")
                    .singleBtn(true)
                    .contentGravity(Gravity.CENTER)
                    .cancelable(true)
                    .show();
        });
        mDataBinding.imgTip2.setOnClickListener(v -> {
            new RoundDialog.Builder(this)
                    .title("提示")
                    .content("企业电子签章的负责人")
                    .confirm("知道了")
                    .singleBtn(true)
                    .contentGravity(Gravity.CENTER)
                    .cancelable(true)
                    .show();
        });
        mDataBinding.btnCancel.setOnClickListener(v -> finish());
        mDataBinding.btnOpen.setOnClickListener(v -> {
            if (TextUtils.isEmpty(mDataBinding.edPhone.getText())) {
                mDataBinding.txtTipPhone.setText("请输入手机号码");
                mDataBinding.txtTipPhone.setVisibility(View.VISIBLE);
                return;
            }
            if (!isChinaPhoneLegal(mDataBinding.edPhone.getText().toString())) {
                mDataBinding.txtTipPhone.setText("手机号码格式错误");
                mDataBinding.txtTipPhone.setVisibility(View.VISIBLE);
                return;
            }
            if (TextUtils.isEmpty(mDataBinding.verificationCode.getText())) {
                showTipCodeTxt("请输入验证码");
                return;
            }
            if (!isGetCode) {
                showTipCodeTxt("验证码不存在，请获取验证码");
                return;
            }
            if (TextUtils.isEmpty(mDataBinding.name.getText())) {
                mDataBinding.txtTipName.setVisibility(View.VISIBLE);
                return;
            }
            if (TextUtils.isEmpty(mDataBinding.idNum.getText())) {
                showTipIdTxt("请输入身份证号码");
                return;
            }
            if (!StringUtils.idCardValidate(mDataBinding.idNum.getText().toString())) {
                showTipIdTxt("身份证号码格式错误");
                return;
            }
            if (!isAgree) {
                MToast.showToast(OpenAccountActivity.this, "请勾选用户协议");
                return;
            }

            bean = new OpenAccountEntity();
            bean.validateCode = mDataBinding.verificationCode.getText().toString();
            bean.creditCode = mDataBinding.companyNo.getText().toString();
            bean.identityCard = mDataBinding.idNum.getText().toString();
            bean.name = mDataBinding.name.getText().toString();
            bean.phone = mDataBinding.edPhone.getText().toString();
            mViewModel.openAccount(OpenAccountActivity.this, bean);
        });
        listener();
        mViewModel.getCompanyDetail(this);
    }

    private void listener() {
        mViewModel.openAccount.observe(this, type -> {
            if ("1".equals(type)) {
                new RoundDialog.Builder(this)
                        .title("提示")
                        .content("恭喜您，在线合同签约账户已开通")
                        .confirm("立即查看").confirmCallback(v -> {
                    finish();
                    startActivity(new Intent(OpenAccountActivity.this, AccountDetailActivity.class));
                })
                        .singleBtn(true)
                        .contentGravity(Gravity.CENTER)
                        .cancelable(false)
                        .show();
            } else {
                showTipCodeTxt(type.toString());
            }

        });
        mViewModel.code.observe(this, type -> {
            startTimer();
        });
        mViewModel.detail.observe(this, type -> {
            mDataBinding.companyName.setText(type.companyName);
            mDataBinding.companyNo.setText(type.creditCode);
        });
        mViewModel.error.observe(this, error -> {
            showTipIdTxt(error.toString());
        });
    }

    public void showTipCodeTxt(String tx) {
        mDataBinding.txtTipCode.setText(tx);
        mDataBinding.txtTipCode.setVisibility(View.VISIBLE);
    }

    public void showTipIdTxt(String tx) {
        mDataBinding.txtTipId.setText(tx);
        mDataBinding.txtTipId.setVisibility(View.VISIBLE);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            if (v.getId() == R.id.ed_phone) {
                mDataBinding.txtTipPhone.setVisibility(View.GONE);
            } else if (v.getId() == R.id.verification_code) {
                mDataBinding.txtTipCode.setVisibility(View.GONE);
            } else if (v.getId() == R.id.name) {
                mDataBinding.txtTipName.setVisibility(View.GONE);
            } else if (v.getId() == R.id.id_num) {
                mDataBinding.txtTipId.setVisibility(View.GONE);
            }
        }
    }

    public static boolean isChinaPhoneLegal(String phone) throws PatternSyntaxException {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[0-9]))\\d{8}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            return isMatch;
        }
    }

    private void startTimer() {
        CountDownTimer timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mDataBinding.getCode.setEnabled(false);
                String str = String.format("重新获取(%1$d)", millisUntilFinished / 1000);
                mDataBinding.getCode.setText(str);
                mDataBinding.getCode.setTextColor(getResources().getColor(R.color.color_C0C4CC));
            }

            @Override
            public void onFinish() {
                mDataBinding.getCode.setEnabled(true);
                mDataBinding.getCode.setText("获取验证码");
                mDataBinding.getCode.setTextColor(getResources().getColor(R.color.color_ffb79255));
            }
        };
        timer.start();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!TextUtils.isEmpty(mDataBinding.edPhone.getText().toString())) {
            mDataBinding.txtTipPhone.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(mDataBinding.verificationCode.getText().toString())) {
            mDataBinding.txtTipCode.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(mDataBinding.idNum.getText().toString())) {
            mDataBinding.txtTipId.setVisibility(View.GONE);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
    }

    /**
     * 验证输入的名字是否为“中文”或者是否包含“·”
     */
    public boolean isLegalName(String name) {
        if (name.contains("·") || name.contains("•")) {
            if (name.matches("^[\\u4e00-\\u9fa5]+[·•][\\u4e00-\\u9fa5]+$")) {
                return true;
            } else if (name.matches("[\\u4e00-\\u9fa5]+[·•]")) {
                return true;
            } else {
                return false;
            }
        } else {
            if (name.matches("^[\\u4e00-\\u9fa5]+$")) {
                return true;
            } else {
                return false;
            }
        }
    }
}
